import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import {isAuthentication} from "@/utils/usertoken"
import {getMenuTree} from "@/api/sys/menuapi"

//动态构建路由表
const buildRoutes = async () => {

    //构建过一次就不用做了
    const {data} = await getMenuTree();
    console.log("构建路由，要到菜单数据",data.data)

    //0、准备一个数组
    const menuRoutes = new Array();

    //所有菜单的子菜单全部构建到 menuRoutes 中
    for (let ele of data.data) {
        for (let childEle of ele.children) {
            menuRoutes.push({
                path: childEle.menuUrl,   // sys/user
                name: childEle.menuName,
                component: () => import(`/src/views${childEle.menuUrl}.vue`)
            })
        }
    }


    //给session中保存
    sessionStorage.setItem("allroutes",JSON.stringify(menuRoutes))

    // //删除dashboard 之前的旧路由关系，准备新的 Dashboard 路由表
    // router.removeRoute('Dashboard')
    //
    // 构建到路由中
    router.addRoute({
        path: '/',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        children: menuRoutes
    });

    //返回构建好的子路由
    return menuRoutes;

}
const getAllRoutes = ()=>{
    let json = sessionStorage.getItem("allroutes");
    if(json == null){
        console.log("没有构建过路由")

        return  buildRoutes();
    }

    //如果不为null
    let parse = [...JSON.parse(json)];
    for (let ele of parse) {
        ele.component =  () => import(`/src/views${ele.path}.vue`)
    }
    console.log("构建过路由，直接用session中的数据即可，第一次要自己做好 component 属性",parse)
    return parse;
}


const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/login',
            name: 'Login',
            component: () => import('@/views/Login.vue')
        },
        {
            path: '/',  //默认得有
            name: 'Dashboard',
            component: () => import('@/views/Dashboard.vue'),
            children: getAllRoutes(),
        }
    ]
})


router.beforeEach(async (to, from) => {
    //检查是否有令牌，且合法
    let isAuthenticated = await isAuthentication();
    if (!isAuthenticated && to.name !== 'Login') {
        // 检查用户是否已登录 && ❗️ 避免无限重定向
        // 将用户重定向到登录页面
        //  return {name: 'Login'}
       return  {name: 'Login'}
    }

    if(isAuthenticated) {
        buildRoutes();
    };


})





// router.beforeEach(to => {
//     if (!hasNecessaryRoute(to)) {
//         router.addRoute(generateRoute(to))
//         // 触发重定向
//         return to.fullPath
//     }
// })

export default router
